package com.quick.proxy.client.handler;

import com.quick.proxy.client.ProxyClient;
import com.quick.proxy.client.ProxyMessageAuthHandler;
import com.quick.proxy.core.handler.ProxyChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Description: 连接处理程序
 * Author: 吃素不吃肉
 * Date: 2023/7/9
 *
 * @author 吃素不吃肉
 */
@Component
@Sharable
@Slf4j
public class ConnectHandler extends ProxyChannelInboundHandlerAdapter {
    @Autowired
    private ProxyClient proxyClient;

    @Autowired
    private ProxyMessageAuthHandler proxyMessageAuthHandler;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("proxy client error.", cause);

    }

    /**
     * 客户端去和服务端连接成功时触发
     *
     * @param ctx 上下文
     * @throws Exception 异常
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //发起认证请求
        proxyMessageAuthHandler.authRequest(ctx);
        super.channelActive(ctx);
    }

    /**
     * 客户端去和服务端失去连接时触发
     *
     * @param ctx 上下文
     * @throws Exception 异常
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        if (ctx.channel().isOpen()) {
            ctx.channel().close();
        }
        log.warn("Proxy client disconnects and starts connecting in 10 seconds");
        ctx.channel().eventLoop().schedule(() -> {
            log.warn("Proxy client is reconnecting");
            proxyClient.start();
        }, 10, TimeUnit.SECONDS);
        super.channelInactive(ctx);
    }
}
